﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utility
{
    public class SocketClient 
    {
        public static string SendRequest(string requestStr, ref string error)
        {
            string result = null;
            if (string.IsNullOrWhiteSpace(GLOBAL.IPAddress) || string.IsNullOrWhiteSpace(GLOBAL.IPPort))
            {
                error = "IP或端口缺失";
                return result;
            }
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse(GLOBAL.IPAddress);
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, Convert.ToInt32(GLOBAL.IPPort))); //配置服务器IP与端口  
            }
            catch
            {
                error = "连接失败";
                return error;
            }
            byte[] buffer = new byte[4096];

            try
            {
                clientSocket.ReceiveTimeout = 30000;
                clientSocket.Send(Encoding.ASCII.GetBytes(RSAHelper.RsaEncrypt(requestStr, GLOBAL.PUBLICCSHARPKEY)));

                //通过clientSocket接收数据  
                int receiveLength = clientSocket.Receive(buffer);

                result = RSAHelper.RSADecryptByJAVAPublicKey(Encoding.GetEncoding("GBK").GetString(buffer, 0, receiveLength), GLOBAL.PUBLICJAVAKEY);
            }
            catch (Exception ex)
            {
                error = "异常：" + ex.Message;
                WriteLog.WriteExceptionFile("Socket Client SendRequest Method Exception ：" + error);
            }
            finally
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            return result;
        }
    }
}
